package com.example.demo.controller;

import com.example.demo.service.EmailService;
import com.example.demo.service.RedisService;
import jakarta.annotation.Resource;
import lombok.val;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController("auth")
public class AuthController {

    @Resource
    private EmailService emailService;
    @Resource
    private RedisService redisService;

    @PostMapping("auth")
    public Map<String, Object> auth(@RequestParam("email") String email, @RequestParam("k") int k) {
        Map<String, Object> map = new HashMap<>();
        Long time = this.redisService.getTime("AUTH" + k + email);
        if (k == 1 || k == 2) {
            if (time != null && time > 9 * 60) {
                map.put("msg", "请不要频繁获取验证码！");
                map.put("code", "500");
                return map;
            }
            val sendMailForTemplateEngine = this.emailService.sendMailForTemplateEngine(email, k);
            if (sendMailForTemplateEngine) {
                map.put("msg", "验证码发送成功！");
                map.put("code", "200");
            } else {
                map.put("msg", "验证码发送失败！");
                map.put("code", "500");
            }
        } else {
            map.put("msg", "k值错误！");
            map.put("code", "401");
        }
        return map;
    }
}
